let axios = require('axios');
let cheerio = require('cheerio');
let fs = require('fs')
let taskRun=require('./taskRun')
class qianka {
  constructor() {
    this.app = {}
    this.threadPool = {};
    this.performTasks()
  }
  getUserInfo(userName, cookie) {
    return new Promise((resolve, reject) => {
      this.setting(userName, cookie)
      this.instance.get(`https://qianka.com/s4/users.profiles.getInfo`).then(res => {
        if (res.data.err_code === 0) {
          console.log(res.data.payload.id)
          res.data.payload.id
          res.data.payload.wx_nickname
          res.data.payload.nickname
          res.data.payload.wx_nickname
          resolve({
            success: true,
            userInfo: {
              id: res.data.payload.id,
              wx_nickname: res.data.payload.wx_nickname,
              nickname: res.data.payload.nickname,
              wx_nickname: res.data.payload.wx_nickname
            }
          })
        } else {
          reject({
            success: false,
            message: res.data
          })
        }
      }).catch(err => {
        reject({
          success: false,
          message: err
        })
      })
    })
  }
  async applyTask(userName, cookie, type, cb) {
    console.log('applyTask申请添加修改任务...')
    try {
      let result = await this.getUserInfo(userName, cookie)
      if (result.success) {
        this.userInfo = result.userInfo
        this.userId = this.userInfo.id;
        let userId = this.userId;
        if (!this.threadPool[`k-${userId}`]) {
          // 任务添加
          this.threadPool[`k-${userId}`] = {
            id: userId,
            userName,
            cookie,
            userInfo: this.userInfo,
            history: [],
            activate: type
          }
          cb({
            success: true,
            message: '任务添加成功'
          })
        } else {
          // 任务修改
          this.threadPool[`k-${userId}`].activate = type
          cb({
            success: true,
            message: '任务修改成功'
          })
        }
      } else {
        cb({
          success: true,
          message: result.message
        })
      }
    } catch (err) {
      cb({
        success: false,
        message: err.message.message ? err.message.message : err.message
      })
    }


  }

  // 执行任务
  performTasks() {
    console.log(`performTasks执行任务...`)
    let taskList = []
    for (let key in this.threadPool) {
      if (this.threadPool[key].activate) {
        taskList.push(this.threadPool[key])
      }
    }
    console.log(`${new Date().getTime()}扫描到${taskList.length}个待执行任务`)
    if (taskList.length) {
      for (let i = 0; i < taskList.length; i++) {
        console.log(taskList[i].id)
        // this.taskRun(taskList[i]);
        new taskRun(taskList[i], res => {
          console.log(i)
          console.log(res)
        });
      }
    }
    setTimeout(() => {
      this.performTasks();
    }, 5000)
    // this.instance.get(`https://qianka.com/s4/lite.subtask.start?task_id=${id}&quality=0`).then(res => {
    //   console.log(res.data)
    // }).catch(err => {
    //   console.log(err)
    // })
  }

  getTaskList(cb) {
    this.instance.get(`/s4/lite.subtask.list`).then(res => {
      cb({
        success: true,
        res
      })
    }).catch(err => {
      cb({
        success: false,
        err
      })
    })
  }

  setting(userName, cookie) {
    this.user = {
      name: userName,
      cookie
    }
    this.headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Host': 'qianka.com',
      'Cookie': cookie,
      'Accept': 'application/json, text/plain, */*',
      'User-Agent': `Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16C101 version=2.0.2018091801 bid=com.kka.video`
    }


    this.instance = axios.create({
      baseURL: 'https://qianka.com',
      headers: this.headers
    });
  }

  updataTask(userName, cookie, cb) {
    this.setting(userName, cookie)
    this.cb = cb
    console.log('正在扫描任务...')
    this.getTaskList(data => {
      try {
        this.newTaskId = 0
        if (data.success) {
          console.log('---------------------------')
          let tasks = [].concat(data.res.data.payload.tasks || []).concat(data.res.data.payload.newbie || [])
          let flag = false;

          this.tasks = [];
          for (let i = 0; i < tasks.length; i++) {
            if (tasks[i].is_pay === 0) {
              this.tasks.push(tasks[i]);
            }
            if (tasks[i].status === 2) {
              flag = true;
              this.currentTaskId = tasks[i].id;
              this.currentTaskIndex = i;
            }
          }

          if (this.tasks.length && flag === false && this.tasks[0].qty > 0) {
            this.newTaskId = this.tasks[0].id;
            console.log(`发现新任务:${this.tasks[0].title}:${this.newTaskId}`);
            this.cb({
              message: `发现新任务:${this.tasks[0].title}:${this.newTaskId}`
            })
            // this.applyTask(this.newTaskId)
          } else if (flag === true) {
            console.log(`任务${this.currentTaskId}进行中...`)
            console.log(`appurl:${this.app.url}`)
            this.getTaskDetail();
            // return false;
          } else if (this.tasks.length === 0) {
            this.cb({
              message: 1
            })
          } else {
            this.cb({
              message: 0
            })
          }
        } else {
          this.cb({
            message: data.err.message
          })
          console.error(data.err)
        }
      } catch (err) {
        this.cb({
          message: err
        })
      }
    })
  }

  getTaskDetail() {
    this.taskDetail = {}
    this.instance.get(`/s4/lite.subtask.detail?task_id=${this.currentTaskId}`).then(res => {
      this.taskDetail = res.data.payload;
      this.searchAppUrl();
      console.log(`appName:${this.taskDetail.app_name}`)
    }).catch(err => {
      console.log(err)
    })
  }

  singIn() {
    console.log('开始签到...');
    this.instance.post(`/s5/reward.coin.claim.today`).then(res => {
      console.log('签到成功!!!')
      setTimeout(() => {
        this.singIn()
      }, 2000)
    }).catch(err => {
      console.log(err.response.data.err_msg)
      if (err.response && err.response.data && err.response.data.err_msg && err.response.data.err_msg === '今日已经领取过了') {
        console.log('已签到!!!')
      } else {
        setTimeout(() => {
          this.singIn()
        }, 2000)
      }
    })
  }

  searchAppUrl() {
    console.log('searchAppUrl...')
    let url = encodeURI(`https://www.chandashi.com/search/index?keyword=${this.taskDetail.app_name.split(/[—（,-]/)[0]}&type=store&country=cn`)
    console.log(url)
    axios.get(url).then(res => {
      try {
        let $ = cheerio.load(res.data);
        let list = $('#searchlist .searchlist.bottom-div');
        if (list && list.length) {
          let index = -1;
          for (let i = 0; i < list.length; i++) {
            let title = $(list[i]).find('a').attr('title').replace(/\s/g, '')
            if (title === this.taskDetail.app_name.replace(/\s/g, '')) {
              index = i;
              break;
            }
          }
          if (index !== -1) {
            this.app.id = $(list[index]).find('a').attr('href').match(/\/appId\/\d+?\/country/)[0].match(/\d+/)[0]
            this.app.name = $(list[index]).find('a').attr('title').trim()
            this.app.src = $(list[index]).find('a img').attr('src');
          } else {
            let a=$($('#searchlist .searchlist.bottom-div .pic')[0])
            this.app.id = a.attr('href').match(/\/appId\/\d+?\/country/)[0].match(/\d+/)[0]
            this.app.name = a.attr('title').trim()
            this.app.src = a.find('img').attr('src');
          }
          this.app.url = `https://itunes.apple.com/cn/app/id${this.app.id}`
          this.taskDetail.newAppName = this.app.name
          this.taskDetail.newAppImg = this.app.src;
          this.taskDetail.newAppId = this.app.id
          this.taskDetail.newAppSrc = this.app.url
          this.cb(this.taskDetail);
        } else {
          this.taskDetail.code = 404;
          this.taskDetail.message = '暂未查到此应用'
          this.cb(this.taskDetail)
        }
      } catch (err) {
        console.log(err)
      }
    }).catch(err => {
      console.log(err)
    })

  }
}




module.exports = new qianka();
